package apies;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.os.AsyncTask;
import android.util.Log;

public class Connection extends AsyncTask<Void, Void, String> {
	private String _sURL;
	private List<BasicNameValuePair> _params;
	private String result;

	public Connection(String url, List<BasicNameValuePair> params)
			throws MalformedURLException {
		_sURL = url;
		_params = params;
		result = new String("");
	}

	@Override
	protected String doInBackground(Void... arg0) {
		try {
			HttpClient client = new DefaultHttpClient();
			HttpPost post = new HttpPost(_sURL);
			post.setEntity(new UrlEncodedFormEntity(_params));

			// http response
			HttpResponse response = client.execute(post);
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent(), "utf-8"));
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine())!=null)
				sb.append(line + System.getProperty("line.separator"));
			
			result = sb.toString();
			
		} catch (UnsupportedEncodingException e) {
			result = "UnsupportedEncodingException: " + e.toString();
			Log.d("conn", e.toString());
		} catch (ClientProtocolException e) {
			result = "ClientProtocolException: " + e.toString();
			Log.d("conn", e.toString());
		} catch (IOException e) {
			result = "IOException: " + e.toString();
			Log.d("conn", e.toString());
		}
		return result;
	}
	
	@Override
	protected void onPostExecute(String result) {
		// TODO Auto-generated method stub
		super.onPostExecute(result);
	}
	
	public String getResult() {
		return result;
	}

}
